<template>
    <div class="reservation-list">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="query" class="demo-form-inline" size="small">
            <el-form-item label="活动名称">
                <el-input v-model="query.eventName" placeholder="请输入活动名称" clearable>
                    <template #prefix
                        ><el-icon class="el-input__icon"><Search /></el-icon
                    ></template>
                </el-input>
            </el-form-item>
            <el-form-item label="用户昵称">
                <el-input v-model="query.nickName" placeholder="请输入用户昵称" clearable>
                    <template #prefix
                        ><el-icon class="el-input__icon"><Search /></el-icon
                    ></template>
                </el-input>
            </el-form-item>
            <el-form-item label="类型" v-if="user && [1,2].includes(user.role)">
                <el-select v-model="query.type" placeholder="请选择类型" clearable>
                <el-option
                    v-for="(label, value) in roleType"
                    :key="value"
                    :label="label"
                    :value="value"
                />
                </el-select>
            </el-form-item>
            <el-form-item label="状态" >
                <el-select v-model="query.status" placeholder="请选择状态" clearable>
                    <el-option label="待审核" value="待审核" />
                    <el-option label="审核通过" value="审核通过" />
                    <el-option label="审核失败" value="审核失败" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loadReservations">查询</el-button>
                <el-button type="danger" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 预约数据表格 -->
        <el-table :data="reservations" stripe border v-loading="loading" :max-height="getTableHeight()">
            <el-table-column prop="reservationId" label="预约ID" sortable />
            <el-table-column prop="nickName" label="用户昵称" />
            <el-table-column prop="name" label="场地名" />
            <el-table-column prop="reservationDate" label="预约日期">
                <template #default="scope">
                    {{ formatDate(scope.row.reservationDate) }}
                </template>
            </el-table-column>
            <el-table-column prop="times" label="时间">
                <template #default="scope">
                    {{ formatTimes(scope.row.times) }}
                </template>
            </el-table-column>
            <el-table-column prop="role" label="类型">
                <template #default="{ row }">{{ roleType[row.role] }}</template>
            </el-table-column>
            <el-table-column prop="eventName" label="活动名称" />
            <el-table-column prop="numPeople" label="人数" />
            <el-table-column prop="status" label="状态" />
            <el-table-column fixed="right" label="操作" width="120">
                <template #default="scope">
                    <el-button size="small" @click="viewDetails(scope.row)">查看详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />

        <!-- 预约详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="预约详情">
            <el-descriptions :column="1">
                <el-descriptions-item label="预约ID">{{ currentReservation.reservationId }}</el-descriptions-item>
                <el-descriptions-item label="用户">{{ currentReservation.username }}</el-descriptions-item>
                <el-descriptions-item label="场地">{{ currentReservation.name }}</el-descriptions-item>
                <el-descriptions-item label="预约日期">{{ formatDate(currentReservation.reservationDate) }}</el-descriptions-item>
                <!-- <el-descriptions-item label="开始时间">{{ currentReservation.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ currentReservation.endTime }}</el-descriptions-item> -->
                <el-descriptions-item label="时间">{{ currentReservation.times }}</el-descriptions-item>
                <el-descriptions-item label="活动名称">{{ currentReservation.eventName }}</el-descriptions-item>
                <el-descriptions-item label="人数">{{ currentReservation.numPeople }}</el-descriptions-item>
                <el-descriptions-item label="状态">{{ currentReservation.status }}</el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <span class="dialog-footer">
                    <span v-if="pageName !== 'MyReserations'">
                        <el-button type="success" @click="approveReservation" :disabled="currentReservation.status !== '待审核'"
                            >同意</el-button
                        >
                        <el-button type="danger" @click="rejectReservation" :disabled="currentReservation.status !== '待审核'"
                            >驳回</el-button
                        >
                    </span>
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { Search, User, Location } from '@element-plus/icons-vue';
import { formatTimes, formatDate } from '../utils/time';
import { useRoute } from 'vue-router';
import { roleType, getTableHeight } from '../utils/role';
import moment from 'moment';

// 响应式数据
const reservations = ref([]); // 预约数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示条数
const total = ref(0); // 总记录数
const loading = ref(false); // 加载状态
const query = reactive({
    eventName: '', // 活动名称
    nickName: '', // 用户ID
    type: '',
    status: '',
}); // 查询条件
const user = ref(null);

const detailDialogVisible = ref(false); // 预约详情对话框是否显示
const currentReservation = ref({}); // 当前查看的预约详情

// 加载预约数据
const loadReservations = async () => {
    loading.value = true; // 开始加载
    try {
        const params = {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            ...query,
        };
        const userString = sessionStorage.getItem('user');
        const userObj = userString ? JSON.parse(userString) : null;
        user.value = userObj
        if (pageName.value === 'MyReserations') {
            const userId = userObj ? userObj.id : null;
            params.userId = userId;
            params.role = params.type
        } else {
            if ([3, 4, 5].includes(userObj.role)) {
                params.role = userObj.role;
            }else {
                params.role = params.type
            }
        }
        const response = await axios.get('http://localhost:8080/api/reservations/list', {
            params,
        });
        if (response.data.status === 200) {
            // 如果响应状态码为200，表示查询成功
            reservations.value = response.data.data.records; // 设置预约数据
            total.value = response.data.data.total; // 设置总记录数
        } else {
            // 如果响应状态码不为200，表示查询失败
            ElMessage.error(response.data.message || '获取预约信息失败'); // 显示错误信息
        }
    } catch (error) {
        // 如果发生错误
        ElMessage.error('获取预约信息失败: ' + error.message); // 显示错误信息
    } finally {
        loading.value = false; // 结束加载
    }
};

// 重置查询条件
const resetQuery = () => {
    Object.keys(query).forEach((key) => (query[key] = '')); // 清空查询条件
    currentPage.value = 1; // 重置当前页码为第一页
    loadReservations(); // 重新加载预约数据
};

// 查看预约详情
const viewDetails = (reservation) => {
    currentReservation.value = reservation; // 设置当前查看的预约详情
    detailDialogVisible.value = true; // 显示预约详情对话框
};

// 处理页码改变
const handleCurrentChange = (newPage) => {
    currentPage.value = newPage; // 更新当前页码
    loadReservations(); // 重新加载预约数据
};

// 处理每页显示条数改变
const handleSizeChange = (newSize) => {
    pageSize.value = newSize; // 更新每页显示条数
    loadReservations(); // 重新加载预约数据
};

// 格式化日期和时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return 'N/A'; // 如果日期和时间为空，返回'N/A'
    const d = new Date(dateTime); // 创建日期对象
    return isNaN(d.getTime()) ? 'Invalid Date' : d.toLocaleString(); // 如果日期无效，返回'Invalid Date'，否则返回本地日期和时间字符串
};

// 同意预约
const approveReservation = async () => {
    try {
        // 确认对话框
        await ElMessageBox.confirm('确定要同意这个预约吗？', '确认', {
            confirmButtonText: '确定', // 确认按钮文本
            cancelButtonText: '取消', // 取消按钮文本
            type: 'warning', // 对话框类型
        });

        // 更新预约状态
        const updateResponse = await axios.put('http://localhost:8080/api/reservations/update', {
            ...currentReservation.value, // 当前预约详情
            username: undefined,
            name: undefined,
            nickName: undefined,
            status: '审核通过', // 更新状态为'审核通过'
        });
        if (updateResponse.data.status === 200) {
            // 如果更新状态成功
            // 创建通知
            const date = moment(currentReservation.value.reservationDate).format('YYYY-MM-DD');
            const notificationResponse = await axios.post('http://localhost:8080/api/tongzhi/create', {
                title: `预约通知：${currentReservation.value.eventName}`, // 通知标题
                content: `预约已通过！预约详情：日期${date}，时间${currentReservation.value.times}点,${currentReservation.value.eventName},人数：${currentReservation.value.numPeople}.`, // 通知内容
                userId: currentReservation.value.userId, // 用户ID
                venueId: currentReservation.value.venueId,
            });

            if (notificationResponse.data.status === 200) {
                // 如果创建通知成功
                ElMessage.success('预约已同意，并已发送通知'); // 显示成功信息
                currentReservation.value.status = '审核通过'; // 更新当前预约状态为'审核通过'
                await loadReservations(); // 重新加载预约数据
                detailDialogVisible.value = false; // 关闭预约详情对话框
            } else {
                throw new Error(notificationResponse.data.message || '通知发送失败'); // 抛出错误
            }
        } else {
            throw new Error(updateResponse.data.message || '预约更新失败'); // 抛出错误
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('操作失败: ' + error.message); // 显示错误信息
        }
    }
};

// 驳回预约
const rejectReservation = async () => {
    try {
        await ElMessageBox.confirm('确定要驳回这个预约吗？', '确认', {
            confirmButtonText: '确定', // 确认按钮文本
            cancelButtonText: '取消', // 取消按钮文本
            type: 'warning', // 对话框类型
        });

        const response = await axios.put('http://localhost:8080/api/reservations/update', {
            ...currentReservation.value, // 当前预约详情
            username: undefined,
            name: undefined,
            nickName: undefined,
            status: '审核失败', // 更新状态为'审核失败'
        });

        if (response.data.status === 200) {
            const date = moment(currentReservation.value.reservationDate).format('YYYY-MM-DD');
            const notificationResponse = await axios.post('http://localhost:8080/api/tongzhi/create', {
                title: `预约通知：${currentReservation.value.eventName}`, // 通知标题
                content: `预约已驳回！预约详情：日期${date}，时间${currentReservation.value.times}点,${currentReservation.value.eventName},人数：${currentReservation.value.numPeople}.`, // 通知内容
                userId: currentReservation.value.userId, // 用户ID
                venueId: currentReservation.value.venueId,
            });

            if (notificationResponse.data.status === 200) {
            // 如果更新状态成功
                ElMessage.success('预约已驳回，并已发送通知'); // 显示成功信息
                currentReservation.value.status = '审核失败'; // 更新当前预约状态为'审核失败'
                await loadReservations(); // 重新加载预约数据
                detailDialogVisible.value = false; // 关闭预约详情对话框
            }
        } else {
            throw new Error(response.data.message || '操作失败'); // 抛出错误
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('操作失败: ' + error.message); // 显示错误信息
        }
    }
};

// 组件挂载时加载数据  MyReserations
const route = useRoute();
const pageName = ref('');
onMounted(() => {
    pageName.value = route.name;
    loadReservations(); // 加载预约数据
});
</script>

<style scoped>
.reservation-list {
    padding: 20px; /* 设置内边距 */
}

.el-pagination {
    margin-top: 20px; /* 设置上边距 */
    justify-content: center; /* 水平居中 */
}

.dialog-footer {
    display: flex; /* 设置为弹性布局 */
    justify-content: flex-end; /* 内容靠右对齐 */
    gap: 10px; /* 设置元素之间的间隔 */
}
</style>
